<template>
    <div class="layout-padding">
        <splitpanes horizontal>
            <pane size='50'>
                <div class="layout-padding-auto layout-padding-view">
                    <el-tabs model-value="first">
                        <el-tab-pane name="first">
                            <template #label>
                                <span class="ml-0.5">
                                    {{ $t('wms.checkStockHeader') }}
                                </span>
                            </template>
                        </el-tab-pane>
                    </el-tabs>
                    <!--查询条件表单-->
                    <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
                        <el-form-item :label="$t('wms.billcode')" prop="billCode">
                            <el-input v-model="state.queryForm.billCode" clearable
                            :placeholder="$t('form.pleaseInput', [$t('wms.billcode')])" />
                        </el-form-item>

                        <el-form-item :label="$t('edijob.creationTime')" prop="creationTime">
                            <div class="block">
                                <el-date-picker v-model="creationTime" :clearable="false" type="daterange" unlink-panels
                                    range-separator="To" start-placeholder="Start date" end-placeholder="End date"
                                    :shortcuts="shortcuts" />
                            </div>
                        </el-form-item>

                        <el-form-item>
                            <el-button icon="el-icon-search" type="primary" @click="query">{{ $t('fg.query')}}</el-button>
                            <el-button icon="refresh" @click="resetQuery">{{ $t('fg.reset') }}</el-button>
                            <el-button icon="plus" :loading="btnLoading" type="success" @click="createOrder">{{ $t('checkStock.create') }}</el-button>
                            <el-button icon="check" type="success" plain @click="startOrder(selectObjs)">{{ $t('checkStock.start') }}</el-button>
                            <el-button icon="RefreshLeft" type="warning" @click="unAuditOrder(selectObjs)">{{ $t('checkStock.unAudit') }}</el-button>
                            <el-button icon="SwitchButton" type="info" @click="closeOrder(selectObjs)">{{ $t('checkStock.closing') }}</el-button>
                            <el-button icon="delete" type="danger" @click="deleteOrder(selectObjs)">{{ $t('checkStock.delete') }}</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-dropdown>
                                <el-button type="primary" icon="download" plain>
                                    {{ $t('checkStock.export') }}
                                    <el-icon class="el-icon--right">
                                        <arrow-down />
                                    </el-icon>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item @click="exportCheck(selectObjs)">{{ $t('checkStock.ExportList') }}</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </el-form-item>
                    </el-form>


                    <el-table :data="state.dataList" highlight-current-row v-loading="state.loading" border
                        style="width: 100%; height: 100%" :cell-style="tableStyle.cellStyle" @row-click="clickRow"
                        stripe :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangeHandle">

						<el-table-column type="selection" width="40" align="center" />
                        <el-table-column type="index" label="#" width="80" />
                        <el-table-column prop="billCode" :label="$t('checkStock.billcode')" />
						<el-table-column prop="status" :label="$t('checkStock.status')">
							<template #default="scope">
								<el-tag :type="getTagAttrByStatus(scope.row.status).type" :effect="getTagAttrByStatus(scope.row.status).effect">
									{{ getCheckStatusItemText(scope.row.status) }}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="createUserName" :label="$t('checkStock.createUserName')" />
						<el-table-column prop="creationTime" :label="$t('qms.creationTime')" />
						<el-table-column prop="closeCaseTime" :label="$t('checkStock.closeCaseTime')" />
						<el-table-column prop="closeCaseName" :label="$t('checkStock.closeCaseName')" />
                        <el-table-column prop="auditSign" :label="$t('checkStock.auditSign')" width="180">
                            <template #default="scope">
                            <el-button icon="view" type="primary" plain @click="clickPreviewImage(scope.row.auditSign)"
                                v-if="scope.row.auditSign">{{ $t('qms.Preview') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
                        v-bind="state.pagination" />
                </div>
            </pane>
            <pane size='50'>
                <div class="layout-padding-auto layout-padding-view">
                    <el-tabs model-value="first">
                        <el-tab-pane name="first">
                            <template #label>
                                <span class="ml-0.5">
                                    {{ $t('wms.wms.checkStockDetail') }}
                                </span>
                            </template>
                        </el-tab-pane>
                    </el-tabs>
                    <detail ref="detailRef" @refresh="getDataList(false)" />
                </div>
            </pane>
        </splitpanes>
        <div class="demo-image__preview">
            <el-image-viewer class="el-image-viewer" v-if="showImagePreview" :zoom-rate="1.2" @close="closePreview"
                :url-list="imgPreviewList" />
        </div>
    </div>
</template>

<script setup lang="ts">
const detail = defineAsyncComponent(() => import('./detail.vue'));
import { BasicTableProps, useTable } from '/@/hooks/table';
import { getAssetCardCheckStockList, createAssetCardCheckStockOrder, startAssetCardCheckStockOrder, deleteAssetCardCheckStockOrder, closeAssetCardCheckStockOrder,unAuditAssetCardCheckStockOrder } from '/@/api/platform/wms/assetCardCheckStock';
import { ref, reactive } from 'vue';
import { useBizDict } from '/@/hooks/bizDict';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const btnLoading = ref()// 按钮加载状态

const today = new Date();
const endDate = new Date(today);
endDate.setDate(today.getDate() - 1); // 今天之后的6天，总共一周
let creationTime = ref([endDate, today]);
const detailRef = ref()

const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            return [start, end];
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            return [start, end];
        },
    },
];
const getYMD = (date: any) => {
    // 获取年份
    const year = date.getFullYear();

    // 获取月份，注意JavaScript中的月份是从0开始的，因此需要+1
    const month = String(date.getMonth() + 1).padStart(2, '0');

    // 获取日期
    const day = String(date.getDate()).padStart(2, '0');

    // 拼接成 yyyy-MM-dd 格式的字符串
    const formattedDate = `${year}-${month}-${day}`;

    return formattedDate;
};

// 搜索变量
const queryRef = ref();
//表格的配置
const state: BasicTableProps = reactive<BasicTableProps>({
    queryForm: {
        'startTime' : creationTime.value ? getYMD(creationTime.value[0]) : '',
        'endTime' : creationTime.value ? getYMD(creationTime.value[1]) : ''
    },
    pageList: getAssetCardCheckStockList,
});

const query = () => {
    state.queryForm.StartTime = creationTime.value ? getYMD(creationTime.value[0]) : '';
    state.queryForm.EndTime = creationTime.value ? getYMD(creationTime.value[1]) : '';
    getDataList();
};

//预览图片变量
const imgPreviewList = ref([])
const showImagePreview = ref(false)

//点击预览图片
const clickPreviewImage = async (url: string) => {
  let urls = url?.split(",");
  showImagePreview.value = true
  imgPreviewList.value = urls
}

const closePreview = () => {
  imgPreviewList.value = []
  showImagePreview.value = false
}

// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
// 多选事件
const selectionChangeHandle = (objs: {  }[]) => {
    selectObjs.value = objs;
    multiple.value = !objs.length;
};

//启动盘点
const startOrder = async (rows: Array<number>) => {
    if (rows?.length === 0) {
        return useMessage().error(t('qms.pleaseSelectAPieceOfData'))
    }
    // 遍历检查盘点状态是不是 Create
    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        if (row.status !== 'Create') {
            return useMessage().error(t('wms.noCreateStatus'));
        }
    }
    const idArray: IdArray = rows?.map(item => (item.id));

    useMessageBox()
        .confirm(t(`wms.isStartCheckStockOrder`))
        .then(async () => {
            btnLoading.value = true;
            await startAssetCardCheckStockOrder({
                HeaderIds: idArray,
            }).then(
                (res) => {
                    getDataList();
                    useMessage().success(t('wms.startSuccess'));
                },
                (error) => {
                    useMessage().error(error?.msg || t('wms.startFail'));
                }
            );
            btnLoading.value = false;
        });
}

//反审盘点
const unAuditOrder = async (rows: Array<number>) => {
    if (rows?.length === 0) {
        return useMessage().error(t('qms.pleaseSelectAPieceOfData'))
    }
    // 遍历检查盘点状态是不是 Audited
    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        if (row.status !== 'Audited') {
            return useMessage().error(t('wms.noAuditStatus'));
        }
    }
    const idArray: IdArray = rows?.map(item => (item.id));

    useMessageBox()
        .confirm(t(`wms.isunAuditStockOrder`))
        .then(async () => {
            btnLoading.value = true;
            await unAuditAssetCardCheckStockOrder({
                HeaderIds: idArray,
            }).then(
                (res) => {
                    getDataList();
                    useMessage().success(t('wms.unAuditSuccess'));
                },
                (error) => {
                    useMessage().error(error?.msg || t('wms.unAuditFail'));
                }
            );
            btnLoading.value = false;
        });
}

//删除盘点
const deleteOrder = async (rows: Array<number>) => {
    if (rows?.length === 0) {
        return useMessage().error(t('qms.pleaseSelectAPieceOfData'))
    }
    // 遍历检查盘点状态是不是 Create
    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        if (row.status !== 'Create') {
            return useMessage().error(t('wms.noCreateStatus'));
        }
    }
    const idArray: IdArray = rows?.map(item => (item.id));

    useMessageBox()
        .confirm(t(`operation.permanentDeletion`))
        .then(async () => {
            btnLoading.value = true;
            await deleteAssetCardCheckStockOrder({
                HeaderIds: idArray,
            }).then(
                (res) => {
                    getDataList();
                    detailRef.value.refresh(0)
                    useMessage().success(t('sop.successfullyDeleted'));
                },
                (error) => {
                    useMessage().error(error?.msg || t('wms.deleteFail'));
                }
            );
            btnLoading.value = false;
        });
}

//结案
const closeOrder = async (rows: Array<number>) => {
    if (rows?.length === 0) {
        return useMessage().error(t('qms.pleaseSelectAPieceOfData'))
    }
    // 遍历检查盘点状态是不是 Audited
    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        if (row.status !== 'Audited') {
            return useMessage().error(t('wms.noAuditStatus'));
        }
    }
    const idArray: IdArray = rows?.map(item => (item.id));

    useMessageBox()
        .confirm(t(`wms.isCloseCheckOrder`))
        .then(async () => {
            btnLoading.value = true;
            await closeAssetCardCheckStockOrder({
                HeaderIds: idArray,
            }).then(
                (res) => {
                    getDataList();
                    useMessage().success(t('wms.closeSuccess'));
                },
                (error) => {
                    useMessage().error(error?.msg || t('wms.closeFail'));
                }
            );
            btnLoading.value = false;
        });
}

//创建盘点单
const createOrder = async () => {
    useMessageBox()
        .confirm(t(`wms.IsCreateCheckStockOrder`))
        .then(async () => {
            btnLoading.value = true;
            await createAssetCardCheckStockOrder().then(
                (res) => {
                    getDataList();
                    useMessage().success(t('wms.createSuccess'));
                },
                (error) => {
                    useMessage().error(error?.msg || t('wms.createFail'));
                }
            );
            btnLoading.value = false;
        });
}

//导出
const exportCheck = async(rows: Array<number>) => {
    if (rows?.length === 0) {
        return useMessage().error(t('qms.pleaseSelectAPieceOfData'))
    }
    const idArray: IdArray = rows?.map(item => (item.id));
    downBlobFile('/wms/FixedAssetsExport/FixedAssetsListExport', {
    "headerIds": idArray
  }, 'FixedAssetsExport' + new Date().getTime() + '.xlsx');
}

const statusColorMap = new Map([
	['Create', { type: 'primary', effect: 'plain' }],
	['Checking', { type: 'success', effect: 'plain' }],
	['Audited', { type: 'warning', effect: 'plain' }],
	['Leveling', { type: 'danger', effect: 'plain' }],
	['LevelEnd', { type: 'warning', effect: 'light' }],
	['ERPLeveling', { type: 'danger', effect: 'light' }],
	['Closed', { type: 'info', effect: 'plain' }],
]);
// 通过状态获取tag标签的属性
const getTagAttrByStatus = (status) => {
	return statusColorMap.get(status);
};

// 根据value获取数据字典中的值
const getCheckStatusItemText = (value: string) => {
	// 从数据字典获取盘点的状态
	const { CheckStatus } = useBizDict('CheckStatus');
	if (!CheckStatus.value) {
		return value;
	}
	return CheckStatus.value.find((item: any) => item.value === value)?.text || value;
};

// 点击行的时候触发
const clickRow = (row: any) => {
    detailRef.value.refresh(row.id)
}

const { tableStyle, getDataList, sizeChangeHandle, currentChangeHandle, downBlobFile } = useTable(state);

// 清空搜索条件
function resetQuery() {
    // 清空搜索条件
    queryRef.value?.resetFields();
    const today1 = new Date();
    const endDate1 = new Date(today);
    endDate1.setDate(today1.getDate() - 1); // 今天之后的1
    creationTime.value = [];
    state.queryForm.StartTime =  '';
    state.queryForm.EndTime =  '';
    getDataList(false);
    detailRef.value.refresh(0)
}

</script>

<style scoped lang="scss"></style>

<style scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

::v-deep(.el-image-viewer__mask) {
  opacity: .7 !important;
}
</style>
